package com.yxq.mdt.app.modules.bottomsheet;

import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.goodsdetail.bean.GoodsDetailBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitGoodsBean;
import com.yxq.mdt.app.utils.BuyGoodsNumberInputFilter;
import com.yxq.mdt.app.widgets.tagview.Tag;
import com.yxq.mdt.app.widgets.tagview.TagView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author L
 * @time 2019-10-29
 * @describe 商品规格-底部弹出框$
 */
public class GoodsAttrBottomSheetDialogFragment extends BottomSheetDialogFragment {


    @BindView(R.id.goods_attr_iv_img)
    ImageView goodsAttrIvImg;
    @BindView(R.id.goods_attr_tv_price)
    TextView goodsAttrTvPrice;
    @BindView(R.id.goods_attr_tv_choice)
    TextView goodsAttrTvChoice;
    @BindView(R.id.tv_reduce)
    TextView tvReduce;
    @BindView(R.id.tv_num)
    public EditText tvNum;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.view_number)
    LinearLayout viewNumber;
    @BindView(R.id.goods_attr_btn_submit)
    public Button goodsAttrBtnSubmit;
    @BindView(R.id.goods_attr_iv_close)
    ImageView goodsAttrIvClose;
    Unbinder unbinder;
    GoodsDetailBean goodsDetailBean;
    BottomSheetDialogInterface bottomSheetDialogInterface;
    @BindView(R.id.cart_tv_alert)
    TextView cartTvAlert;
    @BindView(R.id.goods_detail_attr_layout)
    LinearLayout goodsDetailAttrLayout;
    private HashMap<Integer, Integer> checkMap;
    Integer k = 0;

    public void setBottomSheetDialogInterface(BottomSheetDialogInterface bottomSheetDialogInterface) {
        this.bottomSheetDialogInterface = bottomSheetDialogInterface;
    }

    public interface BottomSheetDialogInterface {
        void onclick(GoodsDetailBean.AttrBean attrBean, String attr, int num);
    }

    public GoodsAttrBottomSheetDialogFragment(GoodsDetailBean goodsDetailBean) {
        this.goodsDetailBean = goodsDetailBean;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_goods_attr_bottom_sheet_fragment_dialog, container, false);
        unbinder = ButterKnife.bind(this, view);
        initViews(view);
        return view;
    }

    private void initViews(View view) {
        view.findViewById(R.id.goods_attr_iv_close).setOnClickListener(view1 -> dismiss());
        InputFilter[] filters = {new BuyGoodsNumberInputFilter(goodsDetailBean.getNum())};
        tvNum.setFilters(filters);
        tvReduce.setOnClickListener(view13 -> {
            if (tvNum.getText().length() == 0) {
                tvNum.setText("1");
            }
            long num = Long.parseLong(tvNum.getText().toString());
            if ((num - 1) <= 0) {
                tvNum.setText("1");
            } else {
                tvNum.setText(--num + "");
            }
        });
        tvAdd.setOnClickListener(view12 -> {
            if (tvNum.getText().length() == 0) {
                tvNum.setText("1");
            }
            long num = Long.parseLong(tvNum.getText().toString());
            tvNum.setText(++num + "");
        });
        goodsAttrBtnSubmit.setOnClickListener(view14 -> {
            if (bottomSheetDialogInterface != null) {
                if (tvNum.getText().toString().length() == 0) {
                    ToastUtils.showShort("数量不能为空");
                    return;
                }
                if (goodsDetailBean.getNum() == 0) {
                    ToastUtils.showShort("该商品无货，不能购买");
                    return;
                }
                int num = Integer.parseInt(tvNum.getText().toString());
                if (num == 0) {
                    ToastUtils.showShort("数量不能0");
                    return;
                }
                //最大购买数
                if (num > goodsDetailBean.getNum()) {
                    num = goodsDetailBean.getNum();
                    ToastUtils.showShort(String.format("该商品最多只能买%d件", num));
                    tvNum.setText(num + "");
                    return;
                }

                int size = checkMap.size();
                List<OrderSubmitGoodsBean.GoodsListBean.AttrBean> data = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    OrderSubmitGoodsBean.GoodsListBean.AttrBean attrBean = new OrderSubmitGoodsBean.GoodsListBean.AttrBean();

                    attrBean.setAttr_group_id(goodsDetailBean.getAttr_group_list().get(i).getAttr_group_id());
                    attrBean.setAttr_group_name(goodsDetailBean.getAttr_group_list().get(i).getAttr_group_name());

                    attrBean.setAttr_id(goodsDetailBean.getAttr_group_list().get(i).getAttr_list().get(checkMap.get(i)).getAttr_id());
                    attrBean.setAttr_name(goodsDetailBean.getAttr_group_list().get(i).getAttr_list().get(checkMap.get(i)).getAttr_name());

                    data.add(attrBean);
                }

                bottomSheetDialogInterface.onclick(attrListBean, JSON.toJSONString(data), num);
            }
            dismiss();
        });
        //判断无货
        if (goodsDetailBean.getNum() == 0) {
            cartTvAlert.setVisibility(View.VISIBLE);
            goodsAttrBtnSubmit.setBackgroundResource(R.drawable.shape_button_confirm_enable_selector);
        } else {
            cartTvAlert.setVisibility(View.GONE);
            goodsAttrBtnSubmit.setBackgroundResource(R.drawable.shape_button_confirm_selector);
        }
        checkMap = new HashMap<>();
        for (k = 0; k < goodsDetailBean.getAttr_group_list().size(); k++) {
            checkMap.put(k, 0);
        }
        setGoodsInfo();
    }

    public void setData() {
        goodsDetailAttrLayout.removeAllViews();
        if (goodsDetailBean != null && goodsDetailBean.getAttr() != null && goodsDetailBean.getAttr().size() > 0) {
            for (k = 0; k < goodsDetailBean.getAttr_group_list().size(); k++) {
                View item = LayoutInflater.from(getContext()).inflate(R.layout.layout_goods_detail_attr, null);
                TagView goodsAttrTags = item.findViewById(R.id.goods_attr_tags);
                TextView goodsAttrTvGroupName = item.findViewById(R.id.goods_attr_tv_group_name);

                goodsAttrTags.removeAllTags();
                //规格名称
                goodsAttrTvGroupName.setText(goodsDetailBean.getAttr_group_list().get(k).getAttr_group_name());
                //规格参数
                for (Integer i = 0; i < goodsDetailBean.getAttr_group_list().get(k).getAttr_list().size(); i++) {

                    GoodsDetailBean.AttrGroupListBean.AttrListBean attrListBean = goodsDetailBean.getAttr_group_list().get(k).getAttr_list().get(i);
                    //选中的规格
                    setGoodsInfo();

                    Tag tag = new Tag(attrListBean.getAttr_name());
                    if (checkMap.containsKey(k) && i == checkMap.get(k)) {
                        //选中
                        tag.tagTextColor = getContext().getResources().getColor(R.color.color_font_red);
                        tag.layoutColor = getContext().getResources().getColor(R.color.white);
                        tag.layoutColorPress = getContext().getResources().getColor(R.color.bg_gray);
                        tag.layoutBorderColor = getContext().getResources().getColor(R.color.color_font_red);
                    } else {
                        tag.tagTextColor = getContext().getResources().getColor(R.color.color_font_gray);
                        tag.layoutColor = getContext().getResources().getColor(R.color.white);
                        tag.layoutColorPress = getContext().getResources().getColor(R.color.white);
                        tag.layoutBorderColor = getContext().getResources().getColor(R.color.color_font_gray);
                    }
                    tag.radius = 32f;
                    tag.tagTextSize = 12f;
                    tag.layoutBorderSize = 1f;
                    tag.isDeletable = false;
                    tag.id = k;
                    goodsAttrTags.addTag(tag);
                }
                goodsAttrTags.setOnTagClickListener((position, tag) -> {
                    checkMap.put(tag.id, position);
                    setData();
                });
                goodsDetailAttrLayout.addView(item);
            }
        }
    }

    GoodsDetailBean.AttrBean attrListBean;

    /**
     * 设置规格信息
     *
     * @param
     */
    private void setGoodsInfo() {

        int size = goodsDetailBean.getAttr().size();
        int r = checkMap.size();//规格数组
        int checkIndex = 0;
        for (int j = 0; j < size; j++) {
            //寻找规格坐标
            boolean checked = true;
            checkIndex = j;
            //默认第一个就是选中的规格
            int flag = 0;
            for (int h = 0; h < r; h++) {
                if ((goodsDetailBean.getAttr_group_list().get(h).getAttr_list().get(checkMap.get(h)).getAttr_id() + "").equals(goodsDetailBean.getAttr().get(j).getAttr_list().get(h).getAttr_id() + "")) {
                    flag++;
                }
            }
            if (flag == r) {
                break;
            }
        }
        attrListBean = goodsDetailBean.getAttr().get(checkIndex);
        String imgUrl;
        if (attrListBean.getPic() != null && attrListBean.getPic().length() > 0) {
            imgUrl = attrListBean.getPic();
        } else {
            imgUrl = goodsDetailBean.getPic_list().get(0).getPic_url();
        }
        GlideHelper.setLoadRoundImage(getContext(), imgUrl, R.color.gray, goodsAttrIvImg);

        StringBuffer label = new StringBuffer();
        for (int h = 0; h < r; h++) {
            label.append(attrListBean.getAttr_list().get(h).getAttr_name());
            label.append(" ");
        }
        goodsAttrTvChoice.setText(label.toString());
        //价格
        if (0f == attrListBean.getPrice()) {
            //如果价格为0 显示商品价格
            goodsAttrTvPrice.setText(String.format("￥%.2f", goodsDetailBean.getPrice()));
        } else {
            goodsAttrTvPrice.setText(String.format("￥%.2f", attrListBean.getPrice()));
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        setData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
